package com.kingsoft.miot.bridge.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.kingsoft.miot.bridge.config.WebSecurityConfig;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.kingsoft.miot.bridge.common.CommonResult;
import com.kingsoft.miot.bridge.pojo.manager.ManagerInfo;
import com.kingsoft.miot.bridge.service.manager.ActionGroupRecordService;
import com.kingsoft.miot.bridge.service.manager.ManagerService;
import com.kingsoft.miot.bridge.utils.CookieUtils;
import com.kingsoft.miot.bridge.utils.HttpUtils;

/**
 * 登录登出控制器
 * 
 * @author HUJIANQING
 *
 */
@RestController
public class LoginController extends BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

	// 管理者登录
	@Autowired
	private ManagerService managerService;
	// 权限记录服务
	@Autowired
	private ActionGroupRecordService actionGroupRecordService;

	/**
	 * 登录 返回用户基本信息
	 * 
	 * @param request
	 * @return
	 */
//	@RequestMapping(value = "/data/user/info", produces = "application/json;charset=UTF-8")
//	public String login(HttpServletRequest request) {
//
//		/**
//		 * 1. 登录数据校验referer 金山云已验证 并由前端携带cookie返回相应的数据
//		 */
//		Map<String, Object> data = new HashMap<String, Object>();
//		data.put("email", "");
//		data.put("uid", "");
//		data.put("permision", "");
//		try {
//			// 2. 判断用户session是否含有该数据
////			System.out.println("---------------Cookie:  ");
////			Cookie[] cookies = request.getCookies();
////			for (Cookie c : cookies) {
////				System.out.println(c.getName() + " : " + c.getValue());
////			}
////			System.out.println("---------------session attribute:  ");
////			while(names.hasMoreElements()) {
////				String element = names.nextElement();
////				System.out.println(element +" : " + "");
////			}
//			Cookie uidCookie = CookieUtils.getCookie(request, "uid");
//			Cookie sessionCookie = CookieUtils.getCookie(request, "JSESSIONID");
//			Cookie pwdCookie = CookieUtils.getCookie(request, "pwd");
//			Cookie kscdigestCookie = CookieUtils.getCookie(request, "kscdigest");
////			System.out.println(kscdigestCookie);
//			HttpSession session = getSession(request);
//			if (session.getAttribute("mng_user_access") == null) {
//				if (uidCookie == null || pwdCookie == null || kscdigestCookie == null || sessionCookie == null) {
//					LOGGER.info("登录失败！");
//					return CommonResult.returnLogin(false, 400, "登录失败，校验信息不正确！", data);
//				}
//			} else {
//				return CommonResult.returnLogin(true, 200, "已登录", data);
//			}
//			// 1.用户信息校验
//			String uid = uidCookie.getValue();
//			String sessionID = sessionCookie.getValue();
//			String password = pwdCookie.getValue();
//			String kscdigest = kscdigestCookie.getValue();
//			// 校验token是否 判断是否登录成功 。
//			checkToken(kscdigest);
//			// 通过用户和密码校验
////			ManagerInfo managerInfo = managerService.getByNameAndPwd(Integer.valueOf(uid), password);
////			if (managerInfo == null) {
////				return CommonResult.returnJson(false, 400, "登录失败！");
////			}
//			// 记录
//			session.setAttribute("mng_user_access", uid + "-" + sessionID); // 1
//			ManagerInfo managerInfo = managerService.getManagerInfoById(Integer.valueOf(uid));
//			LOGGER.info("用户: " + uid + " 登录成功！");
//			data.put("email", managerInfo.getManager_info_email());
//			data.put("uid", uid);
//			data.put("permision", "chief_manager");
//			/**
//			 * 创建权限校验主体 用于后续校验
//			 */
//			// 从SecurityUtils中创建一个subject
//			Subject subject = SecurityUtils.getSubject();
//			// 认证提交前准备toekn
//			UsernamePasswordToken token = new UsernamePasswordToken(uid, password);
//			// 记住用户
////			token.setRememberMe(true);
//			// 执行认证登陆
//			subject.login(token);
//			return CommonResult.returnLogin(true, 200, "登录成功", data);
//
//		} catch (Exception e) {
////			e.printStackTrace();
//			LOGGER.error("登录失败!");
//			return CommonResult.returnLogin(false, 500, "登录失败", data);
//		}
//	}

	/**
	 * 登出
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/data/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request) {
		try {
			// 登出
			HttpSession session = getSession(request);
			if (session.getAttribute("mng_user_access") != null) {
				// 注销权限信息
				Subject subject = SecurityUtils.getSubject();
				if (subject != null && subject.getSession() != null) {
					subject.logout();
					return CommonResult.returnJson(true, 200, "登出成功");
				}
			}
			session.removeAttribute("mng_user_access");
			// 注销
			return CommonResult.returnJson(true, 200, "登出成功");
		} catch (Exception e) {
			return CommonResult.returnJson(false, 500, "登出失败,，未知异常");
		}
	}

	/**
	 * 预登陆
	 * 
	 * @return
	 */
	@RequestMapping(value = "/prelogin", produces = "application/json;charset=UTF-8")
	public String loginPre() {
		return CommonResult.returnJson(false, 400, "请先登录!");
	}

	/**
	 * 登录出错
	 * 
	 * @return
	 */
	@RequestMapping(value = "/loginerror", produces = "application/json;charset=UTF-8")
	public String logError() {
		return CommonResult.returnJson(false, 500, "登录出错!");
	}

	/**
	 * 校验token是正确
	 * 
	 * @param kscdigest
	 * @return
	 */
	private String checkToken(String kscdigest) {
		String retMsg = null;
		try {
			Map<String, String> paraMap = new HashMap<>();
			paraMap.put("Content-Type", "Application/json");
			paraMap.put("X-Entry", "com.ksyun.miot");
			paraMap.put("X-Entry-Secret", "e5f2583741a90cb952912bc3b5db19c2");
			paraMap.put("X-Version", "1");
			paraMap.put("X-Timestamp", "" + new Date().getTime());
			paraMap.put("X-Client-Ip", "10.111.17.83");
			paraMap.put("Expires", "0");
			paraMap.put("Cache-control", "no-cache");
			paraMap.put("Cache", "no-cache");
			String reqUrl = "http://api.passport.ksyun.com/login_tokens/" + kscdigest;
			System.out.println(reqUrl);
			retMsg = HttpUtils.sendGet(reqUrl, null, paraMap);
		} catch (Exception e) {
//			e.printStackTrace();
		}
		return retMsg;
	}

}
